﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarbonExchange.WebControls;
using CarbonExchange.Bll;
using System.Globalization;

public partial class UserControls_CarbonFootprintQuestion_Energy_Electricity : CarbonExchange.WebControls.AuditQuestionBase
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        rdoElectricBills.SelectedIndexChanged += new EventHandler(rdoElectricBills_SelectedIndexChanged);
        rptTvs.ItemDataBinding += new EventHandler<CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs>(rptTvs_ItemDataBinding);
        rptComputers.ItemDataBinding += new EventHandler<AmeeRepeater.ItemEventArgs>(rptComputers_ItemDataBinding);
        rptAppliances.ItemDataBinding += new EventHandler<AmeeRepeater.ItemEventArgs>(rptAppliances_ItemDataBinding);
        rptOthers.ItemDataBinding += new EventHandler<AmeeRepeater.ItemEventArgs>(rptOthers_ItemDataBinding);
        dsOvens.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsOvens_Select);
    }

    void dsOvens_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        AmeeDataCatagoryFactory factory = new AmeeDataCatagoryFactory();
        var hobs = factory.GetByPath("home/appliances/cooking/hob", null);
        var ovens = factory.GetByPath("home/appliances/cooking/oven", null);

        var tmp = hobs.Choices.Select(x => new { Text = GetChoiceDisplayText(string.Concat(x, " Hob")), Value = string.Concat(hobs.Path, "?", hobs.ChoiceName, "=", x) });
        tmp = tmp.Union(ovens.Choices.Select(x => new { Text = GetChoiceDisplayText(string.Concat(x, " Oven")), Value = string.Concat(ovens.Path, "?", ovens.ChoiceName, "=", x) }));
        e.SetData(tmp);
    }

    void rptAppliances_ItemDataBinding(object sender, AmeeRepeater.ItemEventArgs e)
    {
        AmeeDrillDown ameeAppliance = e.Item.FindControl("ameeAppliance") as AmeeDrillDown;
        TextBox txtNumber = e.Item.FindControl("txtNumber") as TextBox;
        if (ameeAppliance != null && txtNumber != null)
        {
            ameeAppliance.AddOptions(Answer.GetSetting<AmeeDrillDown.Option[]>(string.Format("ameeAppliance_{0}", e.Item.ItemIndex)));
            txtNumber.Text = Answer.GetSetting<string>(string.Format("txtNumber_{0}", e.Item.ItemIndex));
        }
    }

    void rptComputers_ItemDataBinding(object sender, AmeeRepeater.ItemEventArgs e)
    {
        AmeeDrillDown ameeComputer = e.Item.FindControl("ameeComputer") as AmeeDrillDown;
        TextBox txtNumber = e.Item.FindControl("txtNumber") as TextBox;
        DropDownList ddlComputerStandby = e.Item.FindControl("ddlComputerStandby") as DropDownList;
        if (ameeComputer != null && txtNumber != null && ddlComputerStandby != null)
        {
            ameeComputer.AddOptions(Answer.GetSetting<AmeeDrillDown.Option[]>(string.Format("ameeComputer_{0}", e.Item.ItemIndex)));
            txtNumber.Text = Answer.GetSetting<string>(string.Format("txtNumber_{0}", e.Item.ItemIndex));
            ddlComputerStandby.Text = Answer.GetSetting<string>(string.Format("ddlComputerStandby_{0}", e.Item.ItemIndex));
        }
    }

    void rptOthers_ItemDataBinding(object sender, AmeeRepeater.ItemEventArgs e)
    {
        AmeeDrillDown ameeOther = e.Item.FindControl("ameeOther") as AmeeDrillDown;
        TextBox txtNumber = e.Item.FindControl("txtNumber") as TextBox;
        DropDownList ddlOtherStandby = e.Item.FindControl("ddlOtherStandby") as DropDownList;
        if (ameeOther != null && txtNumber != null && ddlOtherStandby != null)
        {
            ameeOther.AddOptions(Answer.GetSetting<AmeeDrillDown.Option[]>(string.Format("ameeOther_{0}", e.Item.ItemIndex)));
            txtNumber.Text = Answer.GetSetting<string>(string.Format("txtNumber_{0}", e.Item.ItemIndex));
            ddlOtherStandby.Text = Answer.GetSetting<string>(string.Format("ddlOtherStandby_{0}", e.Item.ItemIndex));
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
    }

    private void rptTvs_ItemDataBinding(object sender, CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs e)
    {
        var answerItemName = string.Concat("TV_", e.Item.ItemIndex);
        AmeeDrillDown ameeTV = e.Item.FindControl("ameeTV") as AmeeDrillDown;
        TextBox txtTvHours = e.Item.FindControl("txtTvHours") as TextBox;
        if (ameeTV != null && txtTvHours != null)
        {
            ameeTV.AddOptions(Answer.GetSetting<AmeeDrillDown.Option[]>(string.Concat(answerItemName, "_options")));
            txtTvHours.Text = Answer.GetSetting<string>(string.Concat(answerItemName, "_hours"));
        }
    }

    void rdoElectricBills_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (rdoElectricBills.SelectedValue == "1")
        {
            phBills.Visible = true;
            phEstimate.Visible = false;
        }
        else if (rdoElectricBills.SelectedValue == "0")
        {
            phBills.Visible = false;
            phEstimate.Visible = true;
        }
        else
        {
            phBills.Visible = false;
            phEstimate.Visible = false;
        }
    }
    
    public override void DataBind()
    {
        if(!string.IsNullOrEmpty(Answer.GetSetting<string>("rdoGreen")))
            rdoGreen.Text = Answer.GetSetting<string>("rdoGreen");
        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rdoElectricBills")))
            rdoElectricBills.Text = Answer.GetSetting<string>("rdoElectricBills");

        txtStandardLights.Text = Answer.GetSetting<string>("txtStandardLights");
        txtEcoLights.Text = Answer.GetSetting<string>("txtEcoLights");

        rptComputers.SetNumberOfItems(Answer.GetSetting<int>("rptComputers"));
        rptAppliances.SetNumberOfItems(Answer.GetSetting<int>("rptAppliances"));
        rptTvs.SetNumberOfItems(Answer.GetSetting<int>("rptTvs"));
        rptOthers.SetNumberOfItems(Answer.GetSetting<int>("rptOthers"));

        ddlElectricPeriod.SelectedValue = Answer.GetSetting<string>("ddlElectricPeriod");
        txtElectricValue.Text = Answer.GetSetting<string>("txtElectricValue");

        rdoElectricBills_SelectedIndexChanged(rdoElectricBills, EventArgs.Empty);

        base.DataBind();
    }

    protected override bool SaveQuestion()
    {
        var completed = true;
        List<CarbonExchange.Bll.AnswerItem> itemsToKeep = new List<CarbonExchange.Bll.AnswerItem>();
        CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory = new CarbonExchange.Bll.AmeeProfileItemFactory();
        CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();

        Answer.SetSetting<string>("rdoGreen", rdoGreen.SelectedValue);
        Answer.SetSetting<string>("rdoElectricBills", rdoElectricBills.SelectedValue);
        if (rdoElectricBills.SelectedValue == "1")
        {
            if (!SaveElectricityAmount(profileItemFactory, dataCategoryFactory, itemsToKeep))
            {
                completed = false;
            }
        }
        else if (rdoElectricBills.SelectedValue == "0")
        {
            if (!SaveElectricityEstimate(profileItemFactory, itemsToKeep))
            {
                completed = false;
            }
        }
        else
        {
            completed = false;
        }

        var deleteItems = Answer.AnswerItems.Where(x => !itemsToKeep.Contains(x)).ToList();

        if (deleteItems.Count > 0)
        {
            CarbonExchange.Bll.AnswerItemFactory answerItemFactory = new CarbonExchange.Bll.AnswerItemFactory();
            answerItemFactory.Delete(deleteItems);
            foreach (var del in deleteItems)
            {
                if (Answer.AnswerItems.Contains(del))
                    Answer.AnswerItems.Remove(del);
            }
        }
        return completed;
    }

    private bool SaveElectricityAmount(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        Answer.SetSetting<string>("ddlElectricPeriod", ddlElectricPeriod.SelectedValue);
        Answer.SetSetting<string>("txtElectricValue", txtElectricValue.Text);

        string itemName = "ElecticityBills";
        string path = "/home/energy/electricity";
        string choice = "country={0}";
        switch(Audit.Country.RegionInfo.TwoLetterISORegionName)
        {
            case "GB":
                choice = string.Format(choice, "United Kingdom");
                break;
            case "US":
                choice = string.Format(choice, "United States");
                break;
            case "CA":
                choice = string.Format(choice, "Canada");
                break;
            case "AU":
                choice = string.Format(choice, "Australia");
                break;
            case "CH":
                choice = string.Format(choice, "Switzerland");
                break;
            case "IE":
                choice = string.Format(choice, "Ireland");
                break;
            case "HK":
                choice = string.Format(choice, "China (Including Hong Kong)");
                break;
            case "JP":
                choice = string.Format(choice, "Japan");
                break;
            case "AE":
                choice = string.Format(choice, "United Arab Emirates");
                break;
            default:
                choice = string.Format(choice, Audit.Country.RegionInfo.EnglishName);
                break;
        }
        CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = EnsureProfileItem(itemName, profileItemFactory, dataCategoryFactory, path, choice);

        var save = string.IsNullOrEmpty(tmpProfileItem.Id);
        
        int months = 0;
        try
        {
            months = int.Parse(ddlElectricPeriod.SelectedValue);
        }
        catch (FormatException)
        {
        }
        
        int amount = 0;
        try
        {
            amount = int.Parse(txtElectricValue.Text);
        }
        catch (FormatException)
        {
        }

        decimal result = 0m;
        if(months > 0m)
            result = (decimal)amount / (decimal)months;

        if (tmpProfileItem.GetValue<decimal>("kWhPerMonth") != result)
        {
            tmpProfileItem.SetValue<decimal>("kWhPerMonth", result);
            save = true;
        }
        if (save)
        {
            profileItemFactory.Save(tmpProfileItem);
        }


        itemsToKeep.Add(Answer.SetItem(itemName, tmpProfileItem, 1));

        return result > 0;
    }

    private bool SaveElectricityEstimate(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        var complete = true;
        if (!SaveLights(profileItemFactory, itemsToKeep, false))
        {
            complete = false;
        }
        if (!SaveLights(profileItemFactory, itemsToKeep, true))
        {
            complete = false;
        }
        Answer.SetSetting("rptComputers", rptComputers.Items.Count());
        foreach (var item in rptComputers.Items)
        {
            if (!SaveComputerItem(item, profileItemFactory, itemsToKeep))
            {
                complete = false;
            }
        }
        Answer.SetSetting("rptAppliances", rptAppliances.Items.Count());
        foreach (var item in rptAppliances.Items)
        {
            if (!SaveAppliancesItem(item, profileItemFactory, itemsToKeep))
            {
                complete = false;
            }
        }
        Answer.SetSetting("rptTvs", rptTvs.Items.Count());
        foreach (var item in rptTvs.Items)
        {
            if (!SaveTvItem(item, profileItemFactory, itemsToKeep))
            {
                complete = false;
            }
        }
        Answer.SetSetting("rptOthers", rptOthers.Items.Count());
        foreach (var item in rptOthers.Items)
        {
            if (!SaveOtherItem(item, profileItemFactory, itemsToKeep))
            {
                complete = false;
            }
        }
        return complete;
    }

    private bool SaveAppliancesItem(AmeeRepeaterItem item, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        var itemCompleted = true;
        var answerItemName = string.Concat("Appliance_", item.ItemIndex);
        AmeeDrillDown ameeAppliance = item.FindControl("ameeAppliance") as AmeeDrillDown;
        TextBox txtNumber = item.FindControl("txtNumber") as TextBox;
        if (ameeAppliance != null && txtNumber != null)
        {
            Answer.SetSetting(string.Format("ameeAppliance_{0}", item.ItemIndex), ameeAppliance.SelectedOptions);
            Answer.SetSetting(string.Format("txtNumber_{0}", item.ItemIndex), txtNumber.Text);
            if (ameeAppliance.CurrentCategory.DataItemSelected)
            {
                int number = 1;
                try
                {
                    number = int.Parse(txtNumber.Text);
                }
                catch(FormatException)
                {
                }
                var tmpProfileItem = EnsureProfileItem(answerItemName, profileItemFactory, ameeAppliance.CurrentCategory);

                var save = string.IsNullOrEmpty(tmpProfileItem.Id);
                if(save)
                {
                    profileItemFactory.Save(tmpProfileItem);
                }
                itemsToKeep.Add(Answer.SetItem(answerItemName, tmpProfileItem, number));
            }
            else
            {
                itemsToKeep.Add(Answer.SetItem(answerItemName, ameeAppliance.CurrentCategory));
                itemCompleted = false;
            }
        }

        return itemCompleted;
    }

    private bool SaveComputerItem(AmeeRepeaterItem item, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        var itemCompleted = true;
        var answerItemName = string.Concat("Computer_", item.ItemIndex);
        AmeeDrillDown ameeComputer = item.FindControl("ameeComputer") as AmeeDrillDown;
        TextBox txtNumber = item.FindControl("txtNumber") as TextBox;
        DropDownList ddlComputerStandby = item.FindControl("ddlComputerStandby") as DropDownList;
        if (ameeComputer != null && txtNumber != null && ddlComputerStandby != null)
        {
            Answer.SetSetting<AmeeDrillDown.Option[]>(string.Format("ameeComputer_{0}", item.ItemIndex), ameeComputer.SelectedOptions);
            Answer.SetSetting<string>(string.Format("txtNumber_{0}", item.ItemIndex), txtNumber.Text);
            Answer.SetSetting<string>(string.Format("ddlComputerStandby_{0}", item.ItemIndex), ddlComputerStandby.SelectedValue);

            if (ameeComputer.CurrentCategory.DataItemSelected)
            {
                var tmpProfileItem = base.EnsureProfileItem(answerItemName, profileItemFactory, ameeComputer.CurrentCategory);

                int number = 1;
                try
                {
                    number = int.Parse(txtNumber.Text);
                }
                catch (FormatException)
                {
                }

                var save = string.IsNullOrEmpty(tmpProfileItem.Id);

                if (tmpProfileItem.GetValue<string>("onStandby") != ddlComputerStandby.SelectedValue)
                {
                    tmpProfileItem.SetValue<string>("onStandby", ddlComputerStandby.SelectedValue);
                    save = true;
                }

                if (tmpProfileItem.GetValue<int>("numberOwned") != number)
                {
                    tmpProfileItem.SetValue<int>("numberOwned", number);
                    save = true;
                }

                if (save)
                {
                    profileItemFactory.Save(tmpProfileItem);
                }

                itemsToKeep.Add(Answer.SetItem(answerItemName, tmpProfileItem, number));
            }
            else
            {
                itemCompleted = false;
                itemsToKeep.Add(Answer.SetItem(answerItemName, ameeComputer.CurrentCategory));
            }
        }
        else
        {
            itemCompleted = false;
        }
        return itemCompleted;
    }

    private bool SaveLights(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep, bool lowEnergy)
    {
        string path = "/home/lighting/";
        string itemName = null;
        string choices = null;
        string propertyName = null;
        int value = -1;

        if (lowEnergy)
        {
            itemName = "EcoLightBulbs";
            choices = "type=lel";
            propertyName = "noOfLowEnergyLightBulbs";
            Answer.SetSetting<string>("txtEcoLights", txtEcoLights.Text);
            try
            {
                value = int.Parse(txtEcoLights.Text);
            }
            catch (FormatException)
            {
            }
        }
        else
        {
            itemName = "StandardLightBulbs";
            choices = "type=normal";
            propertyName = "noOfLightBulbs";
            Answer.SetSetting<string>("txtStandardLights", txtStandardLights.Text);
            try
            {
                value = int.Parse(txtStandardLights.Text);
            }
            catch (FormatException)
            {
            }
        }

        CarbonExchange.Bll.AnswerItem tmpAnswerItem = Answer.GetItemByName(itemName);
        CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = null;
        if (tmpAnswerItem == null || string.IsNullOrEmpty(tmpAnswerItem.AmeeId))
        {
            CarbonExchange.Bll.AmeeDataCatagoryFactory dataFactory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();
            var tmpDataItem = dataFactory.GetByPath(path, choices);
            if (tmpDataItem == null || !tmpDataItem.DataItemSelected)
            {
                throw new ApplicationException(string.Format("Could not find data item at at {0}?{1}", path, choices));
            }
            else
            {
                tmpProfileItem = profileItemFactory.CreateItem(tmpDataItem, Audit.AuditKey, DateTime.Now.ToString("f"), Audit.StartDate);
            }
        }
        else
        {
            tmpAnswerItem.Name = itemName;
            tmpProfileItem = profileItemFactory.GetByPath(Audit.AuditKey, path, tmpAnswerItem.AmeeId);
        }

        if (tmpProfileItem.GetValue<int>(propertyName) != value)
        {
            tmpProfileItem.SetValue<int>(propertyName, value);
            profileItemFactory.Save(tmpProfileItem);
        }

        tmpAnswerItem = Answer.SetItem(itemName, tmpProfileItem);

        itemsToKeep.Add(tmpAnswerItem);

        return value >= 0;

    }

    private bool SaveTvItem(AmeeRepeaterItem item, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        var itemCompleted = true;
        var answerItemName = string.Concat("TV_", item.ItemIndex);
        AmeeDrillDown ameeTV = item.FindControl("ameeTV") as AmeeDrillDown;
        TextBox txtTvHours = item.FindControl("txtTvHours") as TextBox;
        if (ameeTV != null && txtTvHours != null)
        {
            Answer.SetSetting<AmeeDrillDown.Option[]>(string.Concat(answerItemName, "_options"), ameeTV.SelectedOptions);
            Answer.SetSetting<string>(string.Concat(answerItemName, "_hours"), txtTvHours.Text);
            if (ameeTV.CurrentCategory.DataItemSelected)
            {
                var tmpProfileItem = base.EnsureProfileItem(answerItemName, profileItemFactory, ameeTV.CurrentCategory);

                decimal hours = 0m;
                try
                {
                    hours = int.Parse(txtTvHours.Text);
                }
                catch (FormatException)
                {
                }

                if (tmpProfileItem.GetValue<decimal>("hoursPerMonth") != hours)
                {
                    tmpProfileItem.SetValue<decimal>("hoursPerMonth", hours);
                    profileItemFactory.Save(tmpProfileItem);
                }

                itemsToKeep.Add(Answer.SetItem(answerItemName, tmpProfileItem));
            }
            else
            {
                itemCompleted = false;
                itemsToKeep.Add(Answer.SetItem(answerItemName, ameeTV.CurrentCategory));
            }
        }
        else
        {
            itemCompleted = false;
        }
        return itemCompleted;
    }

    private bool SaveOtherItem(AmeeRepeaterItem item, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        var itemCompleted = true;
        var answerItemName = string.Concat("Other_", item.ItemIndex);
        AmeeDrillDown ameeOther = item.FindControl("ameeOther") as AmeeDrillDown;
        TextBox txtNumber = item.FindControl("txtNumber") as TextBox;
        DropDownList ddlOtherStandby = item.FindControl("ddlOtherStandby") as DropDownList;
        if (ameeOther != null && txtNumber != null && ddlOtherStandby != null)
        {
            Answer.SetSetting<AmeeDrillDown.Option[]>(string.Format("ameeOther_{0}", item.ItemIndex), ameeOther.SelectedOptions);
            Answer.SetSetting<string>(string.Format("txtNumber_{0}", item.ItemIndex), txtNumber.Text);
            Answer.SetSetting<string>(string.Format("ddlOtherStandby_{0}", item.ItemIndex), ddlOtherStandby.SelectedValue);

            if (ameeOther.CurrentCategory.DataItemSelected)
            {
                var tmpProfileItem = base.EnsureProfileItem(answerItemName, profileItemFactory, ameeOther.CurrentCategory);

                int number = 1;
                try
                {
                    number = int.Parse(txtNumber.Text);
                }
                catch (FormatException)
                {
                }

                var save = string.IsNullOrEmpty(tmpProfileItem.Id);

                if (tmpProfileItem.GetValue<string>("onStandby") != ddlOtherStandby.SelectedValue)
                {
                    tmpProfileItem.SetValue<string>("onStandby", ddlOtherStandby.SelectedValue);
                    save = true;
                }

                if (tmpProfileItem.GetValue<int>("numberOwned") != number)
                {
                    tmpProfileItem.SetValue<int>("numberOwned", number);
                    save = true;
                }

                if (save)
                {
                    profileItemFactory.Save(tmpProfileItem);
                }

                itemsToKeep.Add(Answer.SetItem(answerItemName, tmpProfileItem, number));
            }
            else
            {
                itemCompleted = false;
                itemsToKeep.Add(Answer.SetItem(answerItemName, ameeOther.CurrentCategory));
            }
        }
        else
        {
            itemCompleted = false;
        }
        return itemCompleted;
    }

    public override int GetActiveItemsCount()
    {
        var i = 1;
        if (pnlElectricBills.Visible)
            i++;
        if (phBills.Visible)
            i += phBills.Controls.Count;
        else if(phEstimate.Visible)
            i += phEstimate.Controls.Count;
        return i;
    }

    public override int RenderItems(int start, int end, HtmlTextWriter writer)
    {
        throw new NotImplementedException();
    }
}
